package com.ruoyi.base.utils.message;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.ruoyi.base.config.message.MessageConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;

/**
 * 短信工具类
 *
 * @author lcf
 */
@Slf4j
public class MessageUtils {
    @Autowired
    private static MessageUtils messageUtils;
    @Autowired
    private MessageConfig messageConfig;

    /**
     * todo 发送短信验证码
     *
     */
    public static void sendPhoneCode(String phone, String code) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone).setSignName("").setTemplateCode("").setTemplateParam(code);
        Client client = getClient();
        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取客户端
     */
    private static Client getClient() {
        Config config = new Config()
                .setAccessKeyId(messageUtils.messageConfig.getAccessKey())
                .setAccessKeySecret(messageUtils.messageConfig.getSecretKey());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 初始化静态成员
     */
    @PostConstruct
    private void init() {
        messageUtils = this;
    }
}
